package com.rephilo.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * 访问频次限制
 *
 * @author rephilo
 */
@Component
@Slf4j
public class RequestLimitFilter implements GlobalFilter, Ordered {

    private static final Long REQUEST_LIMIT = 20L;

    private static final Integer TIME_LIMIT = 60 * 1000;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 从request对象中获取客户端ip
        if (request.getRemoteAddress() != null) {
            String clientIp = request.getRemoteAddress().getHostString();
            String record = redisTemplate.opsForValue().get(clientIp);
            Long count;
            if (record == null) {
                count = 1L;
                redisTemplate.opsForValue().set(clientIp, count.toString(), TIME_LIMIT, TimeUnit.MILLISECONDS);
            } else {
                count = redisTemplate.opsForValue().increment(clientIp);
                if (count > REQUEST_LIMIT) {
                    // 决绝访问，返回
                    response.setStatusCode(HttpStatus.FORBIDDEN); // 状态码
                    log.info("=====>IP:" + clientIp + " 在黑名单中，将被拒绝访问！");
                    String data = "达到次数限制";
                    DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                    return response.writeWith(Mono.just(wrap));
                }
            }
        }

        // 合法请求，放行，执行后续的过滤器
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
